package com.enterprise.application.mvc.struts.action;

import com.enterprise.application.orm.hibernate.AbstractDaoImpl;
import com.enterprise.support.utility.*;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;


/**
 * Created by IntelliJ IDEA.
 * User: Zhanggaojiang
 * Date: 11-1-19
 * Time: 上午8:41
 * Email: z82422@gmail.com
 * Struts Base Action 所有 Action 都集成此 Action
 */

public class AbstractAction extends ActionSupport implements Preparable {
    protected Logger logger = Logger.getLogger(getClass());
    @Autowired(required = false)
    @Qualifier("abstractDaoImpl")
    public AbstractDaoImpl<Enterprise> logic;

    protected Enterprise input;
    protected ActionContext context;

    protected void push(String key, Object parms) {
        context.getRequest().setAttribute(key, parms);
    }

    /**
     * 是否Post请求
     *
     * @return
     */
    public boolean isPostRequest() {
        return WebUtility.isPostRequest(context.getRequest());
    }

    /**
     * 是否Get请求
     *
     * @return
     */
    public boolean isGetMethod() {
        return WebUtility.isGetRequest(context.getRequest());
    }

    protected boolean isEmpty(Object object, String... equals) {
        return Validation.isEmpty(object, equals);
    }

    public boolean isLoginUser() {
        return UserUtility.isLoginUser(context.getRequest());
    }

    public boolean isLoginAdmin() {
        return UserUtility.isLoginAdmin(context.getRequest());
    }

    protected void setLoginUser(Enterprise enterprise) {
        UserUtility.setLoginUser(context.getRequest(), enterprise);
    }

    protected void setLoginAdmin(Enterprise enterprise) {
        UserUtility.setLoginAdmin(context.getRequest(), enterprise);
    }

    protected <T extends Enterprise> T getUserInfo(Class<T> params) {
        return (T) UserUtility.getUserInfo(context.getRequest());
    }

    protected <T extends Enterprise> T getUserInfo() {
        return (T) UserUtility.getUserInfo(context.getRequest());
    }

    public Enterprise getAdminInfo() {
        return UserUtility.getAdminInfo(context.getRequest());
    }

    public void addFieldError(String fieldName, String errorMessage) {
        super.addFieldError(fieldName, errorMessage);
        if (input.isEmpty("fielderror")) {
            input.set("fielderror", new Enterprise());
        }
        input.getEnterprise("fielderror").set(fieldName, errorMessage);
    }

    protected void showMessageBox(String messageKey) {
        WebUtility.showMsgBox(messageKey);
    }

    public void prepare() throws Exception {
        context = ActionContext.getContext();
        input = context.getRequestAttr("input", Enterprise.class);
    }
}
